package com.yinhai.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.androidquery.util.AQUtility;
import com.lz.util.SystemParsUtils;
import com.lz.util.Utils;
import com.yinhai.cfg.AppConfig;
import com.yinhai.map.ServiceMap;
import com.yinhai.util.UuId;

import java.util.Iterator;
import java.util.Map;

/**
 * @author Juyon 程序入口类
 */
public class MainActivity extends FragmentActivity implements OnClickListener {
    private long firstTime = 0;

    private int selectTabID = 0;

    private int isGroupIndex;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.main);

        Intent chatServer = new Intent(this, MsgService.class);
        startService(chatServer);
        ServiceMap.getMap().put(UuId.getUUID(), chatServer);

        if (Utils.getAutoIsZDHF(this)) {
            Utils.startMsgService(this);
        }

        findViewById(R.id.radio_dial).setOnClickListener(this);
        findViewById(R.id.radio_msg).setOnClickListener(this);
        findViewById(R.id.radio_app).setOnClickListener(this);
        findViewById(R.id.radio_more).setOnClickListener(this);
        findViewById(R.id.radio_contact).setOnClickListener(this);
        // findViewById(R.id.radio_msg).setSelected(true);
        // selectTabID = R.id.radio_msg;
        // setFrame(R.id.radio_msg);
        int index = SystemParsUtils.getInstance(MainActivity.this).getInt("mainIndex", 1);

        onClick(findViewById(mainIndexids[index]));

    }

    private int[] mainIndexids = new int[]{R.id.radio_dial, R.id.radio_msg, R.id.radio_app,
            R.id.radio_more};

    // 设置frame界面
    private void setFrame(int checkedId) {

        FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
        Fragment fragment = FragmentFactory.getInstance().getInstanceById(checkedId);
        if (checkedId == R.id.radio_dial) {
            closedDialNums();

        }
        transaction.replace(R.id.container, fragment);
        transaction.commit();
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.radio_dial && AppConfig.dialHeight == 0) {
            AppConfig.dialHeight = findViewById(R.id.tab).getMeasuredHeight();
        }
        if (selectTabID == R.id.radio_dial && R.id.radio_dial == v.getId()) {
            showDialNums();
        } else {
            closedDialNums();
        }

        if (selectTabID == v.getId()) {
            return;
        }
        if (selectTabID != 0) {
            findViewById(selectTabID).setSelected(false);
        }

//        if (v.getId() == R.id.radio_dial_call) {
//
//            selectTabID = R.id.radio_dial;
//            closedDialNums();
//            findViewById(R.id.radio_dial).setSelected(true);
//            setFrame(R.id.radio_dial);
//            return;
//        }
//        if (v.getId() == R.id.radio_contact_call) {
//
//            selectTabID = R.id.radio_contact;
//            closedDialNums();
//            findViewById(R.id.radio_contact).setSelected(true);
//            setFrame(R.id.radio_contact);
//            return;
//        }

        selectTabID = v.getId();
        v.setSelected(true);
        setFrame(v.getId());
    }


    // 拨打电话
    public void doCall() {
        if (inputNum != null) {
            String telNo = inputNum.getText().toString();
            if (telNo != null && telNo.length() > 0) {
                Uri uri = Uri.parse("tel:" + telNo);
                Intent intent = new Intent(Intent.ACTION_CALL, uri);
                startActivity(intent);
            }
        }
    }

    @Override
    protected void onDestroy() {

        Intent msgServer = new Intent(this, MsgService.class);
        ServiceMap.getMap().put(UuId.getUUID(), msgServer);
        stopService(msgServer);

        if (isTaskRoot()) {
            AQUtility.cleanCacheAsync(this, 0, 0);
        }
        super.onDestroy();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:

                if (dialView.getVisibility() == View.VISIBLE) {
                    closedDialNums();
                    return true;
                }

                long secondTime = System.currentTimeMillis();
                // if (this.getSupportFragmentManager().getBackStackEntryCount() == 0) {
                if (secondTime - firstTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;// 更新firstTime
                    return true;
                } else { // 两次按键小于2秒时，退出应用

                    Map<String, Intent> serviceMap = ServiceMap.getMap();
                    Iterator it = serviceMap.keySet().iterator();
                    while (it.hasNext()) {
                        String key = it.next().toString();
                        stopService(serviceMap.get(key));
                    }
                    finish();
                    // android.os.Process.killProcess(android.os.Process.myPid()); // 获取PID
                    System.exit(0); // 常规java、c#的标准退出法，返回值为0代表正常退出
                    return true;
                }
                // } else {
                // getSupportFragmentManager().popBackStack();
                // }

        }
        return super.onKeyUp(keyCode, event);
    }


    View dialView;
    EditText inputNum;

    private void showDialNums() {

        if (dialView != null) {
            dialView.setVisibility(View.VISIBLE);
        }

        if (mToneGenerator == null) {
            mToneGenerator = new ToneGenerator(AudioManager.STREAM_DTMF, 80); // 设置声音的大小
            setVolumeControlStream(AudioManager.STREAM_DTMF);
        }


        dialView = findViewById(R.id.dial_nums);
        inputNum = (EditText) findViewById(R.id.nums_input);

        findViewById(R.id.dial_nums_hidden).setOnClickListener(onClickListener);

        // 拨号盘数字
        findViewById(R.id.nums_one).setOnClickListener(onClickListener);
        findViewById(R.id.nums_two).setOnClickListener(onClickListener);
        findViewById(R.id.nums_three).setOnClickListener(onClickListener);
        findViewById(R.id.nums_four).setOnClickListener(onClickListener);
        findViewById(R.id.nums_five).setOnClickListener(onClickListener);
        findViewById(R.id.nums_six).setOnClickListener(onClickListener);
        findViewById(R.id.nums_seven).setOnClickListener(onClickListener);
        findViewById(R.id.nums_eight).setOnClickListener(onClickListener);
        findViewById(R.id.nums_nine).setOnClickListener(onClickListener);
        findViewById(R.id.nums_zero).setOnClickListener(onClickListener);
        findViewById(R.id.nums_no).setOnClickListener(onClickListener);
        findViewById(R.id.nums_star).setOnClickListener(onClickListener);
        findViewById(R.id.nums_del).setOnClickListener(onClickListener);


        // 拨号按钮
        findViewById(R.id.dial_button).setOnClickListener(onClickListener);

        dialView.setVisibility(View.VISIBLE);

        inputNum.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                DialFragment fragment = (DialFragment) FragmentFactory.getInstance().getInstanceById(R.id.radio_dial);
                if (fragment != null) {
                    fragment.dialInputText(s);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void closedDialNums() {
        if (dialView != null) {
            inputNum.setText("");
            dialView.setVisibility(View.GONE);
        }


    }

    // 标题按钮点击事件
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                case R.id.nums_one:
                    playTone(ToneGenerator.TONE_DTMF_1);
                    addDialNum('1');
                    break;
                case R.id.nums_two:
                    playTone(ToneGenerator.TONE_DTMF_2);
                    addDialNum('2');
                    break;
                case R.id.nums_three:
                    playTone(ToneGenerator.TONE_DTMF_3);
                    addDialNum('3');
                    break;
                case R.id.nums_four:
                    playTone(ToneGenerator.TONE_DTMF_4);
                    addDialNum('4');
                    break;
                case R.id.nums_five:
                    playTone(ToneGenerator.TONE_DTMF_5);
                    addDialNum('5');
                    break;
                case R.id.nums_six:
                    playTone(ToneGenerator.TONE_DTMF_6);
                    addDialNum('6');
                    break;
                case R.id.nums_seven:
                    playTone(ToneGenerator.TONE_DTMF_7);
                    addDialNum('7');
                    break;
                case R.id.nums_eight:
                    playTone(ToneGenerator.TONE_DTMF_8);
                    addDialNum('8');
                    break;
                case R.id.nums_nine:
                    playTone(ToneGenerator.TONE_DTMF_9);
                    addDialNum('9');
                    break;
                case R.id.nums_zero:
                    playTone(ToneGenerator.TONE_DTMF_0);
                    addDialNum('0');
                    break;
                case R.id.nums_star:
                    playTone(ToneGenerator.TONE_DTMF_S);
                    addDialNum('*');
                    break;
                case R.id.nums_no:
                    playTone(ToneGenerator.TONE_DTMF_P);
                    addDialNum('#');
                    break;
                case R.id.nums_del:
                    deleteNum();
                    break;
                case R.id.dial_nums_hidden:
                    // 隐藏拨号盘
                    closedDialNums();
                    break;
                case R.id.dial_button:
                    doCall();
                    break;
                default:
                    break;
            }
        }
    };


    // 拨数字
    private void addDialNum(char numChar) {
        inputNum.getText().append(numChar);
    }

    // 删除数字
    private void deleteNum() {
        int length = inputNum.getText().length();
        if (length > 0) {
            inputNum.getText().delete(length - 1, length);
        }
    }

    private static final int DTMF_DURATION_MS = 120; // 声音的播放时间
    private Object mToneGeneratorLock = new Object(); // 监视器对象锁

    private ToneGenerator mToneGenerator; // 声音产生器

    /**
     * 播放按键声音
     */
    private void playTone(int tone) {
        // String sound = Utils.getSound(activity);
        if (Utils.getSound(this)) {
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            int ringerMode = audioManager.getRingerMode();
            if (ringerMode == AudioManager.RINGER_MODE_SILENT || ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
                // 静音或者震动时不发出声音
                return;
            }
            synchronized (mToneGeneratorLock) {
                if (mToneGenerator == null) {
                    return;
                }
                mToneGenerator.startTone(tone, DTMF_DURATION_MS); // 发出声音
            }
        } else if (!Utils.getSound(this)) {
            Vibrator vibrator = (Vibrator) getSystemService(Activity.VIBRATOR_SERVICE);
            long[] pattern = {0, 50, 400, 30};
            vibrator.vibrate(pattern, -1);
        }
    }

}
